<template>
  <div class="g_comment c_comment" ref="comment">
    <div class="c_comment__line" ref="commen_line"></div>
    <!-- 工具栏 -->
    <div class="c_comment__utils">
      <div class="utils__left">
        <Icon use="biaoqing" :size="size" @click.stop="showUtils($event, 'emoji')" />
        <Icon use="wenjianjia" :size="size" />
        <Icon use="jianqie1" :size="size" />
        <Icon use="xiaoxi1" :size="size" />
      </div>
      <div class="utils__right">
        <Icon use="dianhua" :size="size" />
        <Icon use="video" :size="size" />
      </div>
      <Expression v-if="showStatus === 'emoji'" class="is_move_open" v-on:PictureToKey="PictureToKey" />
    </div>
    <!-- 输入框  v-html="text" -->
    <div class="c_comment__input" ref="commentRef" Contenteditable="true" @click.stop="setCursor" @input="commentInput"
      :key="'dom'"></div>
    <At v-if="showStatus === 'at'" v-bind="atXY" @selectAtUser="selectAtUser"></At>

    <!-- 按钮 -->
    <div class="c_comment__footer">
      <button class="c_comment__send" @click="submit">发送(S)</button>
    </div>
  </div>
</template>

<script setup>
import Expression from '@/components/Expression/Index.vue'
import At from '@/components/At/Index.vue'
import Icon from '@/components/SVG/index.vue';
import { useTemplateRef, onMounted, ref, nextTick } from 'vue';
import { useUserStore } from '@/pinia/userStore.js';
import { useMouseMove } from '@/hooks/mouseMove.js'
const text = ref("");
const commentRef = useTemplateRef("commentRef")
//showEmoji
const showStatus = ref("");
const moveXY = ref({
  x: 0,
  y: 0
})
const atXY = ref({
  top: 0,
  left: 0
})
const commenLine = useTemplateRef("commen_line")
const comment = useTemplateRef("comment")
const emits = defineEmits(["update:submitComment"])
const userStore = useUserStore();

// 要时刻存储光标位置
// 保存 当前光标所在节点
let cloneRange = null;
let newRange = null;
const size = "1.4em"
let selection = window.getSelection();



// 监听消息输入
function commentInput (e) {
  // 获取光标位置
  text.value = e.target.innerHTML
  let range = selection.getRangeAt(0)
  cloneRange = range.cloneRange();
  // 监听@
  listenerAt()
}

// 选择at用户
function selectAtUser (user) {
  showStatus.value = "";
  selection.removeAllRanges()
  selection.addRange(newRange);
  const text = newRange.extractContents()
  text.data = `$‎{text.data}‎`
  // 创建节点元素
  const elm = document.createElement("at");
  //有个bug 要监听上下左右箭头
  elm.appendChild(text)
  elm.setAttribute("contenteditable", false);
  // elm.tagName = "AT";//标识符
  elm.setAttribute("user", JSON.stringify(user))
  elm.classList.add("g__at")
  newRange.insertNode(elm)
  selection.collapseToEnd();
  newRange = null;

}

// 监听@事件触发
function listenerAt () {
  let range = selection.getRangeAt(0)
  let text = range.commonAncestorContainer.data?.slice(0, range.endOffset);
  const regexp = new RegExp("@\\w*");
  const atObj = regexp.exec(text);
  if (atObj === null) {
    showStatus.value = "";
    return;
  }
  if (newRange === null) {
    newRange = new Range();
    newRange.setStart(range.commonAncestorContainer, range.endOffset - 1)
  }
  newRange.setEnd(range.commonAncestorContainer, range.endOffset)

  if (showStatus.value === "at") {

    return;
  }

  //写的
  showStatus.value = "at";
  // let t = range.extractContents();
  let rect = range.getBoundingClientRect();
  const { left, top } = comment.value.getBoundingClientRect();
  atXY.value = { left: rect.left - left, top: rect.top - top + 20 };

}


// 设置光标位置
function setCursor (e) {
  let range = selection.getRangeAt(0)
  cloneRange = range.cloneRange();
  listenerAt()
}

// 显示工具栏
function showUtils (e, status) {
  moveXY.value.x = e.offsetX;
  showStatus.value = status;

  function _hident () {
    if (showStatus.value === '') {
      window.removeEventListener("click", _hident)
      return;
    }
    showStatus.value = ''
  }

  window.addEventListener("click", _hident);


}
// 选择表情
function PictureToKey (e) {
  let img = document.createElement("img")
  img.src = e.path;
  img.style.width = "30px"
  img.style.verticalAlign = "bottom";
  if (cloneRange == null) {
    commentRef.value.focus()
    cloneRange = selection.getRangeAt(0)
    selection.removeRange(cloneRange);//清楚选中
  }
  cloneRange.insertNode(img)
  // 选择内容  第一个参数是 选择哪个元素  第二个参数  元素内的第几个节点
  selection.collapse(cloneRange.endContainer, cloneRange.startOffset + 1)
  // 更新range
  cloneRange = selection.getRangeAt(0)
  text.value = cloneRange.endContainer.innerHTML

  showStatus.value = false;

}

// 提交消息
function submit (e) {
  if (text.value === '') return alert("内容不能为空");
  let info = {
    type: "CHITCHAT",//什么类型消息
    content: commentRef.value.innerHTML,//消息内容
    time: new Date().getTime(),//消息时间
    // avatar: "https://tse3-mm.cn.bing.net/th/id/OIP-C.sADtiQwtDU-c5UYFmyOxGwHaNK?rs=1&pid=ImgDetMain",//消息头像
    // username: "",//用户名称
    fromId: userStore.user.userId,
    toId: "",//用户id //目标
    status: "success",//消息状态
    isMy: true,
  };
  console.log(cloneRange);

  emits("update:submitComment", info, () => {
    commentRef.value.innerHTML = "";
    text.value = "";
    cloneRange.endContainer.innerHTML = ""
  })

}



onMounted(() => {
  // 初始高度
  useMouseMove(commenLine, (e, coord) => {
    coord.endY = e.screenY;
    let distance = coord.endY - coord.startY;
    coord.startY = e.screenY;
    let oldheight = comment.value.offsetHeight;
    let height = oldheight - distance
    if (height > coord.maxHeight) {
      // comment.value.style.height = coord.maxHeight + 'px';
      return;
    }
    if (height < coord.minHeight) {
      // comment.value.style.height = coord.minHeight + 'px';
      return;
    }
    comment.value.style.height = height + "px";
  }, (e, coord) => {
    coord.startY = e.screenY;
  })

  // selection.selectAllChildren(commentRef.value)


})

</script>
<style>
.g__at {
  background-color: blue;
  color: white;
  margin: 0 4px;
  padding: 6px 10px;
  user-select: none;
  border-radius: 10px;
}
</style>


<style scoped lang="scss">
.c_comment {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  gap: 10px;
  box-sizing: border-box;

  &__line {
    position: absolute;
    top: 0;
    left: 0;
    height: 1px;
    cursor: text;
    width: 100%;
  }

  &__utils {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .utils__left,
    .utils__right {
      display: flex;
      gap: 8px;
    }
  }

  &__input {
    flex: 1;
    border: none;
    outline: none;
    resize: none;
    font-size: 18px;
    background: transparent;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  &__footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  &__send {
    cursor: pointer;
    outline: none;
    border-radius: 4px;
    color: #46cb86;
    background-color: #e9e9e9;
    padding: 6px 20px;

  }
}

.is_move_open {
  // top: v-bind('moveXY.y');
  bottom: 100%;
  left: v-bind('moveXY.x')px;
  transform: translate(-50%, 0);
}

.c_comment__input {
  text-align: left;
}
</style>